package com.atguigu.gmall.product.service.impl;

import com.atguigu.gmall.feign.search.SearchFeignClient;
import com.atguigu.gmall.product.entity.*;
import com.atguigu.gmall.product.service.*;
import com.atguigu.gmall.product.vo.CategoryTreeVo;
import com.atguigu.gmall.search.SearchAttr;
import com.google.common.collect.Lists;

import java.util.ArrayList;
import java.util.Date;

import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.product.vo.SaveSkuInfoVo;
import com.atguigu.gmall.search.Goods;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.gmall.product.mapper.SkuInfoMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoMapper, SkuInfo>
        implements SkuInfoService {

    @Autowired
    SkuInfoService skuInfoService;
    @Autowired
    SkuAttrValueService skuAttrValueService;
    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    SkuImageService skuImageService;
    @Autowired
    StringRedisTemplate redisTemplate;


/*    @Override
    public Page<SkuInfo> getPage(Long page, Long limit) {
        Page<SkuInfo> page1 = new Page<>(page,limit);
        Page<SkuInfo> result = this.lambdaQuery().page(page1);
        result.getRecords();
        result.getCurrent();
        result.getTotal();
        result.getSize();
        result.getPages();
        return result;
    }*/

    @Autowired
    BaseTrademarkService baseTrademarkService;
    @Autowired
    BaseCategoryService baseCategoryService;
    @Autowired
    SearchFeignClient searchFeignClient;

    @Override
    public void onSale(Long skuId) {
/*        LambdaQueryChainWrapper<SkuInfo> wrapper = this.lambdaQuery().eq(SkuInfo::getSpuId, spuId);
        SkuInfo skuInfo = baseMapper.selectOne(wrapper);
        skuInfo.setIsSale((byte) 1);
        baseMapper.updateById(skuInfo);*/

        //修改数据库的上架状态
        boolean update = lambdaUpdate().eq(SkuInfo::getId, skuId).set(SkuInfo::getIsSale, 1).update();
        //准备数据，通过远程调用，更新到es中
        if (update) {
            Goods goods = this.prepareGoods(skuId);
            //远程调用：service-product ==> feign-clients ==> service-search ，更新es
            searchFeignClient.onSale(goods);
            log.info("商品上架成功{}",skuId);
        }
    }

    @Override
    public void cancelSale(Long skuId) {
/*        LambdaQueryChainWrapper<SkuInfo> wrapper = this.lambdaQuery().eq(SkuInfo::getSpuId, spuId);
        SkuInfo skuInfo = baseMapper.selectOne(wrapper);
        skuInfo.setIsSale((byte) 0);
        baseMapper.updateById(skuInfo);*/
        //修改数据库状态
        boolean update = lambdaUpdate().eq(SkuInfo::getId, skuId).set(SkuInfo::getIsSale, 0).update();
        //远程调用，更新es
        searchFeignClient.cancelSale(skuId);
        log.info("商品下架成功{}",skuId);
    }

    //封装了方法，准备商品数据
    public Goods prepareGoods (Long skuId) {
        SkuInfo skuInfo = this.getById(skuId);
        Goods goods = new Goods();
        goods.setId(skuId);
        goods.setDefaultImg(skuInfo.getSkuDefaultImg());
        goods.setTitle(skuInfo.getSkuName());
        goods.setPrice(skuInfo.getPrice().doubleValue());
        goods.setCreateTime(new Date());

        //获取品牌信息
        BaseTrademark baseTrademark = baseTrademarkService.getById(skuInfo.getTmId());
        goods.setTmId(skuInfo.getTmId());
        goods.setTmName(baseTrademark.getTmName());
        goods.setTmLogoUrl(baseTrademark.getLogoUrl());

        //三级分类信息
        CategoryTreeVo categoryTreeVo = baseCategoryService.getCategoryTreeWithC3Id(skuInfo.getCategory3Id());
        goods.setCategory1Id(categoryTreeVo.getCategoryId());
        goods.setCategory1Name(categoryTreeVo.getCategoryName());

        CategoryTreeVo child = categoryTreeVo.getCategoryChild().get(0);
        goods.setCategory2Id(child.getCategoryId());
        goods.setCategory2Name(child.getCategoryName());

        CategoryTreeVo childChild = child.getCategoryChild().get(0);
        goods.setCategory3Id(childChild.getCategoryId());
        goods.setCategory3Name(childChild.getCategoryName());
        //热度分数
        goods.setHotScore(0L);
        //所有 平台属性
        List<SearchAttr> attrs = skuAttrValueService.getSkuAttrsAndValue(skuId);
        goods.setAttrs(attrs);
        return goods;
    }

    @Transactional
    @Override
    public void saveSkuInfo(SaveSkuInfoVo saveSkuInfoVo) {

        //1 保存信息到 sku_info
        SkuInfo skuInfo = new SkuInfo();
        BeanUtils.copyProperties(saveSkuInfoVo, skuInfo);
        this.save(skuInfo);
        Long skuId = skuInfo.getId();

        //2 保存信息到 sku_attr_value
        List<SkuAttrValue> attrValueList = saveSkuInfoVo.getSkuAttrValueList()
                .stream()
                .map(
                        (skuAttrValueListDTO) -> {
                            SkuAttrValue skuAttrValue = new SkuAttrValue();
                            BeanUtils.copyProperties(skuAttrValueListDTO, skuAttrValue);
                            skuAttrValue.setSkuId(skuId);//回填skuId
                            return skuAttrValue;
                        }
                )
                .collect(Collectors.toList());
        skuAttrValueService.saveBatch(attrValueList);

        //3 保存信息到 sku_sale_attr_value
        List<SkuSaleAttrValue> saleAttrValueList = saveSkuInfoVo.getSkuSaleAttrValueList()
                .stream()
                .map(skuSaleAttrValueListDTO -> {
                    SkuSaleAttrValue skuSaleAttrValue = new SkuSaleAttrValue();
                    skuSaleAttrValue.setSkuId(skuId);//回填skuId
                    skuSaleAttrValue.setSpuId(saveSkuInfoVo.getSpuId());
                    skuSaleAttrValue.setSaleAttrValueId(skuSaleAttrValueListDTO.getSaleAttrValueId());
                    return skuSaleAttrValue;
                })
                .collect(Collectors.toList());
        skuSaleAttrValueService.saveBatch(saleAttrValueList);

        //4 保存信息到 spu_image
        List<SkuImage> skuImageList = saveSkuInfoVo.getSkuImageList()
                .stream()
                .map(skuImageListDTO -> {
                    SkuImage skuImage = new SkuImage();
                    BeanUtils.copyProperties(skuImageListDTO, skuImage);
                    skuImage.setSkuId(skuId);//回填skuId
                    return skuImage;
                })
                .collect(Collectors.toList());
        skuImageService.saveBatch(skuImageList);

        //同步到bitmap
        redisTemplate.opsForValue().setBit(RedisConst.SKUID_BITMAP, skuId, true);
    }

}




